package com.mjk.common.util;


import com.mjk.common.tools.logger.BizLogger;

import java.io.IOException;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * 读取jar 包中的文件
 * @author msi
 *
 */
public class JarFileUtils {

	private JarFileUtils() {}

	/**
	 * 读取jar 文件的指定文件的内容
	 * @param jarPath
	 * @param fileName
	 * @return
	 */
	public static String readJarFile(String jarPath,String fileName){		
		JarFile file =null;
		InputStream stream = null;
		try{
			file = new JarFile(jarPath);
			Enumeration<JarEntry> enumeration = file.entries();	
			while(enumeration.hasMoreElements()) {
				JarEntry jarEntry = enumeration.nextElement();
				if(jarEntry.getName().equals(fileName)){
					stream=file.getInputStream(jarEntry);
				}
			}
			if(null == stream){
				return "";
			}
			byte[] bb = new byte[stream.available()];
			stream.read(bb);
			return new String(bb);
		}catch(Exception e){
			BizLogger.error(e);
		}finally{
			if(null!=stream){
				try {
					stream.close();
				} catch (IOException e) {
					BizLogger.error(e);
				}
			}
			if(null!=file){
				try {
					file.close();
				} catch (IOException e) {
					BizLogger.error(e);
				}
			}
		}
		return "";
	}

	/**
	 * 是否是jar文件
	 * @param clazz
	 * @return
	 */
	public static Boolean isJarPath(Class<?> clazz){
		String path = getPath(clazz);
        return path.endsWith("jar");
    }
	
	private static String getPath(Class<?> clazz) {
		String path="";
		URL url = clazz.getProtectionDomain().getCodeSource().getLocation();
		try{
			URLConnection connection = url.openConnection();
			if(connection instanceof JarURLConnection con) {
				JarFile jarFile = con.getJarFile();
				path = jarFile.getName();
				int separator = path.indexOf("!/");
				if (separator > 0) {
					path = path.substring(0, separator);
				}
			} else {
				path = url.getPath();
			}
		}catch(Exception e){
			BizLogger.error(e);
		}
		return path;
	}
}
